import {
  responseSuccess,
  responseError,
} from '@/share/interface/standard';
import { AppDataSource } from '@/data-source';
import { Menu } from '@/entity/Menu';
import type { NextFunction, Request, Response } from 'express';

export class MenuController {
  private menuRepository = AppDataSource.getRepository(Menu);
  /**
   * 获取菜单
   * Method: GET
   */
  async get(req: Request) {
    const menus = await this.menuRepository.find({
      order: { updated: 'asc' },
      relations: ['goods'],
      where: { delete: false },
    });
    return responseSuccess(menus);
  }

  /**
   * 获取菜单数据
   * Method: GET
   */
  async getMenuDetail(req: Request) {
    const id = parseInt(req.params.id);

    const detail = await this.menuRepository.findOne({
      where: { id, delete: false },
      relations: ['goods'],
    });

    return responseSuccess(detail);
  }

  /**
   * 添加菜单
   * Method: post
   */
  async add(req: Request, res: Response) {
    const { name, id } = req.body;

    if (!name) {
      return responseError('菜单名称不能为空');
    }

    const menu = await this.menuRepository.findOne({
      where: { name },
    });
    if (menu) {
      return responseError('菜单已存在');
    }
    await this.menuRepository.save({ name, id });
    return responseSuccess('添加成功');
  }

  /**
   * 更新菜单
   * Method: put
   */
  async put(req: Request, res: Response) {
    const id = parseInt(req.params.id);
    const { name } = req.body;
    const menu = await this.menuRepository.findOne({ where: { id } });
    if (!name) {
      return responseError('菜单名称不能为空');
    }
    if (!menu) {
      return responseError('菜单不存在');
    }
    menu.name = name;
    await this.menuRepository.save(menu);
    return responseSuccess('更新成功');
  }

  /**
   * 删除菜单
   * Method: delete
   */
  async delete(req: Request, res: Response) {
    const id = parseInt(req.params.id);

    const menu = await this.menuRepository.findOne({ where: { id } });
    if (!menu) {
      return responseError('菜单不存在');
    }
    // await this.menuRepository.delete(id);
    await this.menuRepository.update(id, { delete: true });
    return responseSuccess('删除成功');
  }
}
